import requests
from urllib import parse
import base64
import time
import hashlib, hmac
import random
import binascii
import json, os, sys, xlwt
from collections import OrderedDict


class Auth(object):

    def __init__(self, secret_id, secret_key, appid, userid):
        self.AUTH_URL_FORMAT_ERROR = -1
        self.AUTH_SECRET_ID_KEY_ERROR = -2

        self._secret_id = secret_id
        self._secret_key = secret_key
        self._appid = appid
        self._userid = userid

    def app_sign(self, expired=0):
        if not self._secret_id or not self._secret_key:
            return self.AUTH_SECRET_ID_KEY_ERROR

        puserid = ''
        if self._userid != '':
            if len(self._userid) > 64:
                return self.AUTH_URL_FORMAT_ERROR
            puserid = self._userid
 
        now = int(time.time())
        rdm = random.randint(0, 999999999)
        plain_text = 'u=' + puserid + '&a=' + self._appid + '&k=' + self._secret_id + '&e=' + str(expired) + '&t=' + str(now) + '&r=' + str(rdm) + '&f=' 
        bin = hmac.new(self._secret_key.encode(), plain_text.encode(), hashlib.sha1)
        s = bin.hexdigest()
        s = binascii.unhexlify(s)
        s = s + plain_text.encode('ascii')
        signature = base64.b64encode(s).rstrip()    #生成签名
        return signature


def auth(qq="360697611", ):
  AppID = "10154887"
  SecretID = "AKIDnPmtkSQj8JK7g0pzd7OSKyObhcJnu4qP"
  SecretKey = "V8Z2KODoBKDtKWUEixykIbgW7TaS6Vfa"
  cur_time = int(time.time())
  end_time = cur_time + 2 * 60 * 60
  random_str = cur_time

  # AppID = "2011541224"
  # SecretID = "AKID2ZkOXFyDRHZRlbPo93SMtzVY79kpAdGP"
  # SecretKey = "ckKU7P4FwB4PBZQlnB9hfBAcaKZMeUge"
  # qq = "10000"
  # cur_time = "1427786065"
  # end_time = 1432970065
  # random_str = "270494647"
  original = "u={}&a={}&k={}&e={}&t={}&r={}&f=".format(qq, AppID, SecretID, end_time, cur_time, random_str)
  original = original.encode('ascii')
  bin = hmac.new(SecretKey.encode("ascii"), original, hashlib.sha1)
  sha1_hex = bin.hexdigest()
  sha1_hex = binascii.unhexlify(sha1_hex)
  signature = base64.b64encode(sha1_hex + original).rstrip() 
  return signature

def write_data(xls_path, data):
    book = xlwt.Workbook() 

    # font = xlwt.Font()
    # font.blod = True

    # pattern_top = xlwt.Pattern()
    # pattern_top.pattern = xlwt.Pattern.SOLID_PATTERN
    # pattern_top.pattern_fore_colour = 5

    # style = xlwt.XFStyle()
    # style.font = font
    # style.pattern = pattern_top
    # sheet.write_merge(1, 2, 0, 3, 'Second Merge', style)
    # sheet.write_merge(1, 2, 0, 3, 'Second Merge')

    for idx, table in enumerate(data["tableRes"]["tables"]):
      sheet = book.add_sheet(str(idx), cell_overwrite_ok=True)

      for cell in table["cells"]:
        
        text = "" if len(cell["contents"]) == 0 else cell["contents"][0]["itemstring"]
        srow = cell["tl_row"]
        erow = cell["br_row"]
        scol = cell["tl_col"]
        ecol = cell["br_col"]
        if srow < 0 or scol < 0: 
          print(srow, erow, scol, ecol, text)
          continue

        if erow - srow == 1 and ecol - scol == 1:
          sheet.write(srow,scol,text)
        else:
          print(srow, erow, scol, ecol, text)
          sheet.write_merge(srow, erow-1, scol, ecol-1, text)

      # else:
        # sheet.write_merge(, , , , text)

    # for one_row in range(start_idx, total_rows):
    #     row_values = table.row_values(one_row)
    #     stu_id = row_values[2]
    #     data_list = data_lists.get(stu_id, None)
    #     if data_list is None:
    #         print(stu_id, "is None")
    #         continue
        
    #     # for col_idx in range(3, 7):
    #     #     write_excel.write(one_row,col_idx,data_list[col_idx-3])
    #     for col_idx in range(9, 13):
    #         sheet.write(one_row,col_idx,data_list[col_idx-9])

    book.save(xls_path)

def test_ocr(filepath):
  # AppID = "10154887"
  # SecretID = "AKIDnPmtkSQj8JK7g0pzd7OSKyObhcJnu4qP"
  # SecretKey = "V8Z2KODoBKDtKWUEixykIbgW7TaS6Vfa"
  # qq = "360697611"
  # AppID = "2011541224"
  # SecretID = "AKID2ZkOXFyDRHZRlbPo93SMtzVY79kpAdGP"
  # SecretKey = "ckKU7P4FwB4PBZQlnB9hfBAcaKZMeUge"
  # qq = "10000"

  # a = Auth(SecretID, SecretKey, AppID, qq)
  # signature = a.app_sign(2 * 60 * 60)
  AppID = "10154887"
  signature = auth()
  print(signature)


  headers = {
    "Host": "api.youtu.qq.com",
    'Authorization':signature,
    'Content-Type':'text/json'
  }  
  
  url = "https://api.youtu.qq.com/youtu/ocrapi/tableocr"
  # url = "https://api.youtu.qq.com/youtu/ocrapi/characterocr"

  data = {
      "app_id": AppID,
      "image": base64.b64encode(open(filepath, 'rb').read()).rstrip().decode('utf-8'),
      "enable_ret_excel": True
  }


  r = requests.post(url, headers=headers, data=json.dumps(data))
  if r.status_code != 200:
    return {'httpcode':r.status_code, 'errorcode':'', 'errormsg':''}
  r.encoding = "utf-8"
  print(r.encoding)
  ret = r.json()
  with open(filepath + ".json", "w") as wf:
    wf.write(json.dumps(ret))

  write_data(filepath + ".xls", ret)


if __name__ == '__main__':
  # print(auth())

  filepath = sys.argv[1]
  ret = test_ocr(filepath)
